<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\ContactEmployeeTag\Action\Sidebar;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\SidebarAuthMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\ContactEmployeeTag\Contract\ContactEmployeeTagContract;

/**
 * 客户画像 - 添加客户个人标签.
 *
 * Class EmployeeTagStore
 * @Controller
 */
class EmployeeTagStore extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    protected $logger;

    /**
     * @Inject
     * @var ContactEmployeeTagContract
     */
    private $contactEmployeeTagService;

    /**
     * @Middlewares({
     *     @Middleware(SidebarAuthMiddleware::class)
     * })
     * @RequestMapping(path="/sidebar/contactEmployeeTag/employeeTagStore", methods="POST")
     */
    public function handle()
    {
        $user = user();
        // 判断用户绑定企业信息
        if (! isset($user['corpId'])) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        // 接收参数
        $params['tagIds'] = $this->request->input('tagIds');
        $params['contactId'] = (int) $this->request->input('contactId', 0);

        $tags = $this->contactEmployeeTagService->getContactEmployeeTagsByContactId($params['contactId'], ['id', 'contact_tag_id']);

        if (! empty($tags) && array_column($tags, 'contactTagId') === $params['tagIds']) {
            return [];
        }

        // 数据操作
        Db::beginTransaction();
        try {
            $tagIds = $params['tagIds'];
            $data = [];
            if (! empty($tags)) {
                $tagIds = array_diff($params['tagIds'], array_column($tags, 'contactTagId'));
                $delTagIds = array_diff(array_column($tags, 'contactTagId'), $params['tagIds']);
                // 删除标签
                if (! empty($delTagIds)) {
                    $this->contactEmployeeTagService->deleteContactEmployeeTagsByContactIdEmployeeIdTagId($params['contactId'], $user['id'], $delTagIds);
                }
            }
            foreach ($tagIds as $item) {
                $data[] = [
                    'contact_id' => $params['contactId'],
                    'employee_id' => user()['id'],
                    'contact_tag_id' => $item,
                    'created_at' => date('Y-m-d H:i:s'),
                ];
            }
            // 添加标签
            if (! empty($data)) {
                $this->contactEmployeeTagService->createContactEmployeeTagToContact($data);
            }
            Db::commit();
            return [];
        } catch (\Throwable $e) {
            Db::rollBack();
            $this->logger->error(sprintf('%s [%s] %s', '添加个人标签失败', date('Y-m-d H:i:s'), $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
            throw new CommonException(ErrorCode::SERVER_ERROR, $e->getMessage()); // '活动创建失败'
        }
    }

    /**
     * @return string[] 规则
     */
    public function rules(): array
    {
        return [
            'tagIds' => 'required|array',
            'contactId' => 'required|integer|min:1|bail',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    public function messages(): array
    {
        return [
            'tagIds.required' => '标签id 必传',
            'contactId.required' => '客户id必传',
        ];
    }
}
